package bean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.primefaces.event.SelectEvent;

import dao.JPA;
import dao.RoleDAO;
import dao.UserDAO;
import entity.User;

@ManagedBean
@ViewScoped
public class ViewUserListBean {

	@Inject
	@JPA
	private UserDAO userDAO;
	@Inject
	@JPA
	private RoleDAO roleDAO;
	private List<User> resultList;
	@Size(max = 30, message = "Maximum length 30 characters")
	@Pattern(regexp = "[a-zA-Z0-9_-]+", message = "Must contain only letters or numbers")
	private String searchString;
	private List<String> roleList = new ArrayList<>();
	private String selectedRole = "Any";

	@PostConstruct
	private void init() {
		resultList = userDAO.findAll();
		roleList.add("Any");
		roleList.add("None");
		roleList.addAll(roleDAO.selectRoleNames());
	}

	public void onRowSelect(SelectEvent event) {
		int selectedUserId = ((User) event.getObject()).getId();
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("editUser.xhtml?userId=" + selectedUserId);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public void getUserList() {
		if (selectedRole.equals("Any")) {
			if (searchString == null)
				resultList = userDAO.findAll();
			else
				resultList = userDAO.selectUsersByPartName(searchString);
		} else {
			if (searchString == null) {
				if (selectedRole.equals("None"))
					resultList = userDAO.selectUserListByUserPartNameWithNoRoles("_");
				else
					resultList = userDAO.selectUserListByRoleAndUserPartName(selectedRole, "_");
			} else if (selectedRole.equals("None"))
				resultList = userDAO.selectUserListByUserPartNameWithNoRoles(searchString);
			else
				resultList = userDAO.selectUserListByRoleAndUserPartName(selectedRole, searchString);
		}
	}

	public List<String> getRoleList() {
		return roleList;
	}

	public String getSelectedRole() {
		return selectedRole;
	}

	public void setSelectedRole(String selectedRole) {
		this.selectedRole = selectedRole;
	}

	public List<User> getResultList() {
		return resultList;
	}

	public void setResultList(List<User> resultList) {
		this.resultList = resultList;
	}

	public String getSearchString() {
		return searchString;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

}
